package cn.ruauto.log;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author zYu
 * @version 1.0
 * @create 2023-04-08 13:14
 */
public class YuLogInterceptor extends HandlerInterceptorAdapter {
    private  final ThreadLocal<Long> threadLocal = new ThreadLocal<Long>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(handler instanceof HandlerMethod){
            HandlerMethod handler1 = (HandlerMethod) handler;
            Method method = handler1.getMethod();
            YuLog annotation = method.getAnnotation(YuLog.class);
            if(annotation!=null){
                threadLocal.set(System.currentTimeMillis());
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(handler instanceof HandlerMethod) {
            HandlerMethod handler1 = (HandlerMethod) handler;
            Method method = handler1.getMethod();
            YuLog annotation = method.getAnnotation(YuLog.class);
            if (annotation != null) {
                long time = System.currentTimeMillis() - threadLocal.get();
                StringBuffer requestURL = request.getRequestURL();
                String desc = annotation.desc();
                String s = method.getDeclaringClass().getName() + "  " + method.getName();
                System.out.println("本方法执行耗时：" + time);
                System.out.println("本方法的请求路径是：" + requestURL);
                System.out.println("本方法的备注是：" + desc);
                System.out.println("本方法所在位置，以为方法名称是：" + s);
            }
        }
    }
}
